package com.tianhua.amis4j.web.commandline;

import com.coderman.model.meta.bean.back.WebCodeTemplateBean;
import com.tianhua.amis4j.service.admin.WebCodeTemplateConfigService;
import com.tianhua.amis4j.service.enums.WebArchAppEnum;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

/**
 * Description:
 * date: 2022/5/19
 *
 * @author fanchunshuai
 * @version 1.0.0
 * @since JDK 1.8
 */
@Order(value = 1000)
@Component
public class LoadFtlTemplateListener  implements ApplicationListener<ApplicationStartedEvent> {
    private Logger logger = LoggerFactory.getLogger(LoadFtlTemplateListener.class);


    @Autowired
    private WebCodeTemplateConfigService webCodeTemplateConfigService;

    @Override
    public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
        //写文件到项目目录中
        // 获取classpath
        String classpath = null;
        try {
             classpath = ResourceUtils.getURL("classpath:ftl").getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        for (WebArchAppEnum archAppEnum : WebArchAppEnum.values()){
            List<WebCodeTemplateBean> webCodeTemplateBeanList = webCodeTemplateConfigService.getByWebAppName(archAppEnum.getAppCode());
            if(CollectionUtils.isEmpty(webCodeTemplateBeanList)){
                continue;
            }


            for (WebCodeTemplateBean webCodeTemplateBean : webCodeTemplateBeanList){
                if(webCodeTemplateBean.isFtl()){
                    String ftlFilePath = classpath + "/" + webCodeTemplateBean.getWebArchName()+"/"+webCodeTemplateBean.getTemplateName()+".ftl";
                    logger.info("准备写ftl模版内容到项目classpath目录下,ftlFilePath={}",ftlFilePath);
                    try {
                        FileUtils.write(new File(ftlFilePath),webCodeTemplateBean.getTemplateContent(),"utf-8");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }


        }


    }
}
